# -- coding:utf-8 --
import http.server
import json
import sys
from http.server import BaseHTTPRequestHandler, HTTPServer, SimpleHTTPRequestHandler
from urllib.parse import urlparse, parse_qs
import subprocess


def get_port(args):
    if len(args) >= 2:
        if args[0] == "-p" and args[1].isdigit():
            return int(args[1])
    return 2002


class RequestHandler(BaseHTTPRequestHandler):

    def do_GET(self):
        self.status = -1
        self.message = "错误"
        self.send_json()

    def do_POST(self):
        self.status = -1
        self.message = "错误"
        if self.headers['Content-Type'] != 'application/x-www-form-urlencoded':
            self.message = "Content-Type请设置为：application/x-www-form-urlencoded"
            self.send_json()
            return
        content_length = int(self.headers['Content-Length'])
        body = self.rfile.read(content_length)
        params = parse_qs(body.decode())
        if 'act' not in params.keys():
            self.message = "缺少参数act"
            self.send_json()
            return
        act = params['act']
        if len(act) == 0:
            self.message = "缺少参数act"
            self.send_json()
            return

        if act[0] == 'shutdown':
            try:
                # 关机命令
                command = "sudo shutdown -t 60"
                # 执行命令
                process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
                # 获取输出和错误信息
                output, error = process.communicate()
                if process.returncode != 0 and len(error) > 0:
                    print("执行错误")
                    self.message = error.decode('utf-8', 'ignore')
                    self.send_json()
                    return
                self.message = f"[{command}] 执行成功!"
                self.send_json()
                return
            except UnicodeDecodeError as e:
                self.message = str(e)
                self.send_json()
                return

    def send_json(self):
        response = {'status': self.status, 'message': self.message}
        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.end_headers()
        self.wfile.write(json.dumps(response).encode())


if __name__ == '__main__':
    port = get_port(sys.argv[1:])
    host = '0.0.0.0'
    server = http.server.HTTPServer((host, port), RequestHandler)
    # noinspection HttpUrlsUsage
    print(f'服务已启动 http://{host}:{port}')
    print(f"请确保端口{port}处于开放状态")
    server.serve_forever()
